package com.zhiyou100.dao.Impl;

import com.zhiyou100.JDBCUtil.DBUtil;
import com.zhiyou100.dao.ContractDao;
import com.zhiyou100.emtity.Contract;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @description:
 * @author: 马跃
 * @create: 2021-01-23 13:53
 **/
public class ContractDaoImpl implements ContractDao {

    private QueryRunner qur = new QueryRunner(DBUtil.getDataSource());
    @Override
    public List<Contract> queryAll() {
        String sql ="SELECT c.*,h.h_address,h.h_price,l.l_phone\n" +
                "FROM contract c\n" +
                "join lessee l\n" +
                "ON c.l_id=l.l_id\n" +
                "JOIN house h\n" +
                "ON c.h_id=h.h_id\n" +
                "GROUP BY 1";
        try {
            List<Contract> query = qur.query(sql, new BeanListHandler<>(Contract.class));
            return query;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public void add(Contract contract) {
        String sql="insert into contract values(null,?,?,?,?,?,?,?,?,?,?,?,?)";
        try {
            qur.update(sql,
                    contract.getC_number(),
                    contract.getH_id(),
                    contract.getL_id(),
                    contract.getC_time(),
                    contract.getC_beginTime(),
                    contract.getC_endTime(),
                    contract.getC_totalMoney(),
                    contract.getC_method(),
                    contract.getC_deposit(),
                    contract.getC_total(),
                    contract.getC_signatory(),
                    contract.getC_status());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return;
    }

    @Override
    public void delete(int id) {
        String sql = "delete from contract where c_id=?";
        try {
            qur.update(sql, id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return;
    }

    @Override
    public Contract query(int id) {
        String sql = "SELECT c.*,h.h_address,h.h_price,l.l_phone\n" +
                "FROM contract c\n" +
                "join lessee l\n" +
                "ON c.l_id=l.l_id\n" +
                "JOIN house h\n" +
                "ON c.h_id=h.h_id\n" +
                "where c_id=?\n" +
                "GROUP BY 1";
        try {
            Contract query = qur.query(sql, new BeanHandler<>(Contract.class),id);
            return query;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public void update(){

    }
}
